package com.godme.concurrent.block;

import java.util.Random;

public class Sync {


    private final Random random = new Random();


    public synchronized void sleep(String name){
        try{
            System.err.println(name +" : sleeping");
            Thread.sleep(random.nextInt(2000));
            System.err.println(name + " : slept");
        }catch (Exception ignore){}
    }

    static class SyncThread extends Thread{
        private final Sync sync;

        public SyncThread(String name, Sync sync){
            super(name);
            this.sync = sync;
        }

        @Override
        public void run() {
            while (true){
                sync.sleep(getName());
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) {
        Sync sync = new Sync();
        for (int i = 0; i < 5; i++) {
            new SyncThread("thread-"+i, sync).start();
        }
    }
}
